﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "diameterpiechart.h"
#include <QScrollArea>
#include <QGridLayout>
#include "global.h"
#include "preference.h"
#include "serials.h"
#include "mediator.h"
#include "tabledata.h"
#include <regex>
#include <iostream>
#include <QTimer>
#include <QDateTime>
#include <QDesktopServices>
#include <QUrl>
#include <mutex>


//读取字符串代码 @01RD3400000656*
std::mutex mtx_message;
clock_t start_record_time = clock();

QString Convert(std::string str){
    return QString::fromLocal8Bit(str.c_str());
}

MainWindow *pMainWin = nullptr;

#define READ_DM100      1
#define READ_DM102      2


#define FLOAT_DI        "3260"
#define FLOAT_PRE       "3400"
#define INT_BUTTON      "3400"

#define ERROR_DI_MIN   "3064"
#define ERROR_DI_MAX   "3066"


clock_t tickTimeOut = clock();
#define PLCNOP         0
#define PLCREADING     1
#define PLCWRITING     2


std::string WriteValue;
int isReading      = 0;
int CurrentReading = PLCREADING;
bool isRecord = false;
//Excel统计数据
std::vector<XlsData> XlsCensus;

void MainWindow::UpdateUI_Ex(std::string str){

    if(pMainWin)
        pMainWin->UpdateUI(str);
}

int MainWindow::FindWhichClass(double Value)
{


#if 1
    int Class = -1;
    double Base = SIZEPARA[0];
    if(Value < Base){
        return 0;
    }
    double Upper = Base;
    for(int i = 0; i < (MAX_SIZE_OF_DI-1);i++){
        Upper = Base + SIZEPARA[i+1];
        if(Value >= Base && Value<Upper){
            Class = i+1;
            if(Class >= (USER_MAX_SIZE_OF_ID)){
                Class = (USER_MAX_SIZE_OF_ID);
                return Class;
            }

            return Class;
        }
        Base = Upper;
    }

    if(Class >= (USER_MAX_SIZE_OF_ID)){
        Class = (USER_MAX_SIZE_OF_ID);
        return Class;
    }

    if(Class < 0)
        Class = 0;
    return Class;
    std::cout <<"class is "<<Class<<std::endl;
    return MAX_SIZE_OF_DI;
    #else









    int Class = -1;
    double Base = SIZEPARA[0];
    if(Value < Base){
        return 0;
    }
    double Upper = Base;
    for(int i = 0; i < (MAX_SIZE_OF_DI-1);i++){
        Upper = Base + SIZEPARA[i+1];
        if(Value >= Base && Value<Upper){
            Class = i+1;

            if(Class >= USER_MAX_SIZE_OF_ID){
                Class = USER_MAX_SIZE_OF_ID;
                return Class;
            }

            return Class;
        }
        Base = Upper;
    }

    if(Class >= USER_MAX_SIZE_OF_ID){
        Class = USER_MAX_SIZE_OF_ID;
        return Class;
    }

    return MAX_SIZE_OF_DI;

#endif
}


//EXCEL
void MainWindow::UpdateUI(std::string str){
    static std::mutex mtx;
    std::lock_guard<std::mutex> lck(mtx);
    //D 表示直径
    //P 表示压力
    //此处解析EXCEL

//猜测字节位置
    //3400
#define PRESSVALUEBEGIN 7
#define PRESSVALUEEND   8
//3402
#define DVALUEBEGIN     15
#define DVALUEEND       8
//3404
#define DISOK           23
#define DISOKE          8
//3406
#define TENMINOVER      31
#define TENMINBEGIN     8

#define PISOK           15
#define PISOKE          16


#define ISSTRLEN        10
    clock_t nowclk = clock();
    static clock_t oldclk = nowclk;
    static int RecordTime = 0;
    static clock_t start_record_clock = nowclk;

    int Idx = 0;
    int Pos = -1;

#define TOOTHIN     1
#define TOOBIG      2

    static int ThinBig = 0;
    static double  AverageD = 0.0;
    static bool isOpenedOnce = false;
    std::list<double> AverageDRecord;

    Pos = QString::fromStdString(str).indexOf("RD");
    if(str.length() > 16&& Pos > 0)
    {

        float value = 0.0,PreValue = 0.0;
        int TmpValue = 0;
        std::string after_swap,button_swap,pre_swap,dia,pre,button,tenmin;
        QString Number,PreNumber ;
        QDateTime current_time;
        QString StrCurrentTime,CurrentLine,Content;
        int boolButton = 0,boolTempButton = 0;
        static int oldButton = 0,oldTempButton = 0;;

        static clock_t TickSwitch = clock();
        static bool TickRecord = false;
        //逻辑是。。。从无到有超过100才启动，有到无超过100停止
        bool isStartRecord = false;

        //上升沿和下降沿
        bool HasDownStair = false;
        bool HasUpStair = false;
        static int isUpStairState  = 0;
        bool isTrueDown = false;
        bool isSign =false;

        switch (CurrentReading) {
        case PLCREADING:
            dia = str.substr(DVALUEBEGIN,DVALUEEND);

            pre = str.substr(PRESSVALUEBEGIN,PRESSVALUEEND);

            button = str.substr(DISOK,DISOKE);

            tenmin = str.substr(TENMINOVER,8);

            MSerials::SwapLowAndHigh(button,button_swap);
            boolTempButton = QString::fromStdString(button_swap).toInt(NULL,16);

            if(boolTempButton != oldTempButton){
                //boolButton = boolTempButton;
                oldButton = oldTempButton;
                TickSwitch = clock();
                TickRecord = true;
            }


/*
 *--------------- -----------------
 *                      -
 *
 *高电平上突然有一个低电平，用TmpButton ,oldTemp总是上一次的电平信号，如果低电平持续长时间才有效，比如下图
 *
 *
 *------------------                            --------------------
 *                           ------------------
 *
 *
 *
 *------------------                             --
 *                           -------------------   ------------------
 *
  */
          //时间短内，任何跳动的信号都认为无效
            if((clock()-TickSwitch)>FILTERTIME){
                //过了滤波时间，去判断下这个状态
                if(oldButton!=boolTempButton){
                    if(0!=boolTempButton){
                        HasUpStair = true;
                    }
                    else{
                        HasDownStair = true;
                    }
                }
            }


            //判断是否有真正信号输入
            if(HasUpStair){
                if(0==isUpStairState){
                    isUpStairState = 1;
                    isSign = true;
                }
            }else if(HasDownStair){
                if(0!=isUpStairState){
                    isUpStairState = 0;
                    isSign = true;
                }
            }

#if 0
            if(oldButton != boolButton){
                TickSwitch = clock();
                TickRecord = true;
            }
            if(0!=boolButton){
                if(TickRecord){
                    if((clock()-TickSwitch) > FILTERTIME){
                        TickRecord = false;
                    }
                }
            }else{

            }
#endif

           // if(0!=boolButton &&(oldButton != boolButton)){
            if(true == isSign && isUpStairState){

            isRecord = true;
                csv.Init();
                ThinBig = 0;
                AverageD = 0.0;
                AverageDRecord.clear();
                for(auto &item:ValueOfDi){
                    item.second = 0;
                }
                RecordTime = 0;
                isOpenedOnce = true;
                current_time = QDateTime::currentDateTime();
                start_record_time  = clock();
                //
                QString DispTime = Convert("开始记录时间：")+current_time.toString("hh:mm:ss");
                ui->label_DetectStartTime->setText(DispTime);
                ui->label_Tip->setStyleSheet("font-size:45px;color:rgb(0,255,0)");
                ui->label_Tip->setText(Convert("记录中O"));
                ui->label_Status->setStyleSheet("font-size:88px;color:rgb(0,255,0)");
                ui->label_Status->setText(Convert("正常"));
            }
            //else if(0==boolButton){
              else if(true == isSign && !isUpStairState){
                bool isOK = true;
                isRecord = false;
                if(csv.isOpened){
                int LineCensus = csv.CurrentLine() - 1;
                clock_t tenMin = 10*60*1000;
                clock_t setTime = RECTIME*1000;
                clock_t MinTime = setTime < tenMin?setTime:tenMin;
                if(clock()-csv.EstablishClock() > MinTime )
                {
                    ui->label_Tip->setStyleSheet("font-size:45px;color:rgb(255,0,0)");
                    ui->label_Tip->setText(Convert("不记录X"));
                }
                else
                {
                    isOK = false;
                    ui->label_Tip->setStyleSheet("font-size:45px;color:rgb(255,0,0)");
                    std::string Info = "记录无效X";
                    csv.Write(Convert(Info.c_str()));
                    ui->label_Tip->setText(Convert(Info.c_str()));
                }

                csv.Write(Convert("\n统计次数,")+QString::number(LineCensus)+"\n");
                csv.Write(Convert("规格,数量,占比\n"));

                double Total = 0.0;long long Total_Ex = 0;
                for(auto &item:ValueOfDi){
                    Total_Ex += item.second;
                }
                Total = static_cast<double>(Total_Ex);
/*
                int TotalAverage = 0;
                double TotalValue = 0.0;
                for(auto &var : AverageDRecord){
                    TotalValue += var;
                    TotalAverage++;
                }

                if(TotalAverage > 0) AverageD = TotalValue/static_cast<double>(TotalAverage);
                QString DiNum = QString::number(AverageD,'g',5);
*/
                char AverageContent[256] = {0};
                sprintf_s(AverageContent,"平均直径:%6.3fmm\n",AverageD);

                for(auto &item:ValueOfDi){
                    QString Num =QString::number(item.second);
                    QString Ratio = QString::number(item.second*1.0/Total,'g',5);
                    QString Content = Convert(item.first.c_str())+","  + Num  + "," + Ratio + "\n";
                    csv.Write(Content);
                }

                csv.Write(Convert(AverageContent));
                }
                csv.Close();
                if(isOpenedOnce){
                    isOpenedOnce = false;
                    if(0!=ThinBig) isOK = false;

                    if(!isOK){
                        csv.Rename(QString::fromLocal8Bit("不合格"));
                    }else {
                        csv.Rename(QString::fromLocal8Bit("合格"));
                    }
                }


            }

            oldTempButton = boolTempButton;
            //oldButton = boolButton;

            MSerials::SwapLowAndHigh(dia,after_swap);
            TmpValue = QString::fromStdString(after_swap).toLongLong(NULL,16);
            value = *(float*)&TmpValue;
            Number = QString::number(value);
            ui->label_CurrentDi->setText(Convert("直径:")+Number+"mm");

            MSerials::SwapLowAndHigh(pre,pre_swap);
            TmpValue = QString::fromStdString(pre_swap).toLongLong(NULL,16);
            PreValue = *(float*)&TmpValue;
            PreNumber = QString::number(PreValue,'g',4);
            ui->label_CurrentPre->setText(Convert("压力:")+PreNumber+"N");

            //用绝对时间去记录，更为准确
            if(isRecord && ((nowclk - csv.EstablishClock())> 500*RecordTime)){
                RecordTime++;
                //oldclk = nowclk;
                current_time = QDateTime::currentDateTime();
                StrCurrentTime = current_time.toString("yyyy-MM-dd-hh:mm:ss:zzz");
                CurrentLine = csv.GetCurrentLine();
                Content = CurrentLine +"," + StrCurrentTime + "," + Number + ","  + PreNumber + "\n";

                //计算1000个平均值
                AverageDRecord.push_back(value);
                int TotalAverage = 0;
                double TotalValue = 0.0;
                while(AverageDRecord.size()>1000){
                    AverageDRecord.pop_front();
                }
                for(auto &var : AverageDRecord){
                    TotalValue += var;
                    TotalAverage++;
                }
                if(TotalAverage > 0) AverageD = TotalValue/static_cast<double>(TotalAverage);
           //     QString DiNum = QString::number(AverageD,'g',6);
                char AverageContent[256] = {0};
                sprintf_s(AverageContent,"平均直径:%6.3fmm",AverageD);
                std::string S(AverageContent);
                ui->label_AverageDi->setStyleSheet("font-size:20px;color:rgb(125,120,0)");
                ui->label_AverageDi->setText(Convert(S));


                Idx = FindWhichClass(value);
                if(0==Idx ){
                    ThinBig |= TOOTHIN;
                    ui->label_Status->setStyleSheet("font-size:88px;color:rgb(255,0,0)");
                    if(TOOBIG == (TOOBIG & ThinBig)){
                        ui->label_Status->setText(Convert("粗细不均"));
                    }
                    else {
                        ui->label_Status->setText(Convert("丝径偏小"));
                    }

                    ui->label_Status->setText(Convert("丝径不合格"));
                }
                else if(USER_MAX_SIZE_OF_ID <= Idx){
                    ThinBig |= TOOBIG;
                    ui->label_Status->setStyleSheet("font-size:88px;color:rgb(255,0,0)");
                    if(TOOTHIN == (TOOTHIN & ThinBig)){
                        ui->label_Status->setText(Convert("粗细不均"));
                    }
                    else {
                        ui->label_Status->setText(Convert("丝径偏大"));
                    }
                    ui->label_Status->setText(Convert("丝径不合格"));
                }
                else {
                   WriteValue = "0001";
                }

                //数据是否记录
                //if(isRecord) {
                    try {
                        ValueOfDi.at(Idx).second += 1;
                        RefreshTableData(ValueOfDi,-2);
                        DiaPie->UpdateSlice(ValueOfDi);
                    }catch(std::out_of_range ex){

                    }
                    csv.Write(Content);
            }
            break;
        default:
            break;
    }


    }


    else if(str.length()>0){
        ui->label_Error->setText("Er");
    }



}


void MainWindow::RefreshTableData(std::vector<std::pair<std::string, int>> &Items, int Index){
    double QTotal = 0.0;
    try{
        for(auto It:Items){
            QTotal += static_cast<double>(It.second);
        }
        double Var = 0.0;


        if(-2 == Index){

            for(int i = 0;i<ui->tableWidget->rowCount();i++){
                ui->tableWidget->item(i,0)->setText(Convert(Items.at(i).first));
                ui->tableWidget->item(i,1)->setText(QString::number(Items.at(i).second));


                if(QTotal > 0.000001){
                    Var = Items.at(i).second/QTotal;
                    int Data = int(Var*1000);
                    Var = (1.0*Data)/1000.0;
                }
                ui->tableWidget->item(i,2)->setText(QString::number(Var));

            }

            return;
        }

        if(Index > -1)
        {
            if(Index > ui->tableWidget->rowCount()) return;
            ui->tableWidget->item(Index,0)->setText(Convert(Items.at(Index).first));
            ui->tableWidget->item(Index,1)->setText(QString::number(Items.at(Index).second));

            std::cout <<"OK " << Items.at(Index).second <<std::endl;
            if(QTotal > 0.000001){
                Var = Items.at(Index).second/QTotal;
                int Data = int(Var*1000);
                Var = (1.0*Data)/1000.0;
            }
            ui->tableWidget->item(Index,2)->setText(QString::number(Var));
        }
        else {
            ui->tableWidget->setRowCount(Items.size());
            int NumOfReg = ui->tableWidget->rowCount();
            for(int i = 0; i < NumOfReg; i++) {
                int j = 0;
                QTableWidgetItem *item = new QTableWidgetItem();
                item->setBackground(QBrush(QColor(Qt::lightGray)));
                item->setFlags(item->flags() & (~Qt::ItemIsEditable));
                item->setText(Convert(Items.at(i).first));
                ui->tableWidget->setItem(i, j, item);

                j = 1;
                item = new QTableWidgetItem();
                item->setBackground(QBrush(QColor(Qt::lightGray)));
                item->setFlags(item->flags() & (~Qt::ItemIsEditable));
                item->setText(QString::number(Items.at(i).second));
                ui->tableWidget->setItem(i, j, item);

                if(QTotal > 0.000001){
                    Var = Items.at(i).second/QTotal;
                    int Data = int(Var*1000);
                    Var = (1.0*Data)/1000.0;
                }
                j = 2;
                item = new QTableWidgetItem();
                item->setBackground(QBrush(QColor(Qt::lightGray)));
                item->setFlags(item->flags() & (~Qt::ItemIsEditable));
                item->setText(QString::number(Var));
                ui->tableWidget->setItem(i, j, item);
            }


            for(int i = 0;i<Items.size();i++){
                ui->tableWidget->item(i,0)->setText(Convert(Items.at(i).first));
                ui->tableWidget->item(i,1)->setText(QString::number(Items.at(i).second));
                if(QTotal > 0.000001){
                    Var = Items.at(i).second/QTotal;
                    int Data = int(Var*1000);
                    Var = (1.0*Data)/1000.0;
                }
                ui->tableWidget->item(i,1)->setText(QString::number(Var));
            }
        }
        DiaPie->refreshItem(Items);
    }
    catch(std::out_of_range ex){

    }
}

void MainWindow::UpdateData(){
    ValueOfDi.clear();
    double Base = SIZEPARA[0];
    char Msg[256] = {0};
    double Upper = Base;
    sprintf(Msg,"%4.3f-%4.3f",0.0,Base);
    Base = Upper;
    ValueOfDi.push_back(std::pair<std::string,int>(Msg,0.0));
    for(int i = 0;i<(USER_MAX_SIZE_OF_ID-1);i++){
        char Msg[256] = {0};
        Upper = Base+SIZEPARA[i+1];
        sprintf(Msg,"%4.3f-%4.3f",Base,Upper);
        Base = Upper;
        ValueOfDi.push_back(std::pair<std::string,int>(Msg,0.0));
    }
    sprintf(Msg,">%4.3f",Upper);
    ValueOfDi.push_back(std::pair<std::string,int>(Msg,0.0));
    RefreshTableData(ValueOfDi,-1);
    DiaPie->refreshItem(ValueOfDi);
}

unsigned int MainWindow::PLCMessage(void* pVoid){

    return 0;
}

void MainWindow::OnInit(){
     Mediator::GetIns()->UpdateHistory = UpdateUI_Ex;
     RefreshDiv();

     ui->label_Status->setStyleSheet("font-size:88px;color:rgb(255,0,0)");
     ui->label_Status->setText("");

     ui->label_CurrentDi->setStyleSheet("font-size:30px;color:rgb(240,255,240)");
     ui->label_CurrentDi->setText(Convert("当前直径:0mm"));

     ui->label_CurrentPre->setStyleSheet("font-size:30px;color:rgb(240,255,240)");
     ui->label_CurrentPre->setText(Convert("当前压力:0N"));




     QTimer *timer_io = new QTimer();
     //设置定时器每个多少毫秒发送一个timeout()信号    
     timer_io->setInterval(5);

     connect(timer_io, &QTimer::timeout, [=]() {

        if(PLCNOP == isReading)
        {
            isReading = PLCREADING;
            tickTimeOut = clock();
            switch (CurrentReading) {
                case PLCWRITING:
                CurrentReading = PLCREADING;
                Mediator::GetIns()->ReadOutputW("01",FLOAT_PRE,"0006");
                break;
            case PLCREADING:
                CurrentReading = PLCWRITING;
                Mediator::GetIns()->ReadOutputW("01",FLOAT_PRE,"0006");
                break;
            default:
                CurrentReading = PLCREADING;
                Mediator::GetIns()->ReadOutputW("01",FLOAT_PRE,"0006");
                break;
            }
        }

        if((clock()-tickTimeOut) > 2000){
             ui->label_Error->setText("TimeOut");
            isReading = PLCNOP;
        }

        if((clock()-tickTimeOut) > 100){
        {
                         if(!Mediator::GetIns()->Messages.empty()){
                            if(PLCREADING == CurrentReading) UpdateUI(Mediator::GetIns()->Messages.front());
                            std::lock_guard<std::mutex> lck(Mediator::GetIns()->mtx);
                             Mediator::GetIns()->Messages.clear();
                             isReading = PLCNOP;
                         }
            }
        }


     });
     timer_io->start();



/*
    csv.Init();
    sleep(200);
    csv.Close();
    sleep(200);
    csv.Rename(QString::fromLocal8Bit("不合格"));
*/
}


void MainWindow::RefreshDiv(){
    int Div = ui->lineEdit_Divides->text().toInt();
    if(Div > 2 && Div < 11){
        USER_MAX_SIZE_OF_ID = Div;
        UpdateData();

        int i = 0;
        for(auto &pLineEdit:LineEdit){

            if(i<Div){
                pLineEdit->setVisible(true);
            }else{
                pLineEdit->setVisible(false);
            }
            i++;
        }


        i = 0;
        for(auto &pLineEdit:Labels){

            if(i<Div){
                pLineEdit->setVisible(true);
            }else{
                pLineEdit->setVisible(false);
            }
            i++;
        }
        SAVEPRJPARA;
    }else {
#ifdef TEST
    Mediator::GetIns()->WriteOutputW("01",WRITEPLCADDRESS,WRITEPLCLEN);
    this->UpdateUI(std::string("0213333333333333333332432433333333333333333"));
    std::string sw = "FF00AABB";
    std::string end;
    MSerials::SwapLowAndHigh(sw,end);
#endif
    }


}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    HANDLE m_hMutex  =  ::CreateMutexW(NULL, FALSE,  L"PIECHART_FURY" );
    //  检查错误代码
    if  (GetLastError()  ==  ERROR_ALREADY_EXISTS)  {
     QMessageBox::warning(nullptr,QString::fromLocal8Bit("Error"),QString::fromLocal8Bit("请勿多开程序!如果频繁出现，请重启电脑"));
     CloseHandle(m_hMutex);
     m_hMutex  =  NULL;
     exit(0);
    }




    pMainWin = this;
    ui->widget->setStyleSheet("background-color:black;");
    ui->label_Tip->setStyleSheet("font-size:45px;color:rgb(255,0,0)");
    ui->label_Tip->setText("----");

    ui->widget->setStyleSheet("background-color:rgb(16,26,49);");
    ui->widget_ShowError->setStyleSheet("background-color:rgb(16,26,49);");


    char Content[256] = {0};
    sprintf_s(Content,"平均直径:%6.2fmm",0.0);
    std::string S(Content);
    ui->label_AverageDi->setStyleSheet("font-size:20px;color:rgb(125,120,0)");
    ui->label_AverageDi->setText(Convert(S));

    QString DispTime = Convert("开始记录时间：00:00:00");//+current_time.toString("hh:mm:ss");
    ui->label_DetectStartTime->setText(DispTime);



    ui->label_Status->setText(Convert("不合格"));
    ui->lineEdit_FilterTime->setText(QString::number(FILTERTIME));
    connect(ui->lineEdit_FilterTime,&QLineEdit::textChanged,[=](){
        int Time = ui->lineEdit_FilterTime->text().toInt();
        if(Time > 0 && Time < 10000){
            FILTERTIME = Time;
            Preference::GetIns()->prj->WriteSettings();
        }
    });

    ui->lineEdit_RecordTime->setText(QString::number(RECTIME));
    connect(ui->lineEdit_RecordTime,&QLineEdit::textChanged,[=](){
        int Time = ui->lineEdit_RecordTime->text().toInt();
        if(Time > 1 && Time <= 3600){
            RECTIME = Time;
            ui->label_9->setText(QString::fromLocal8Bit("记录时长s"));
            Preference::GetIns()->prj->WriteSettings();
        }else{
            if(Time<1){
                ui->label_9->setText(QString::fromLocal8Bit("设置应大于1"));
            }else{
                ui->label_9->setText(QString::fromLocal8Bit("设置应小于3600"));
            }
           std::cout << "Error"<<std::endl;
        }
    });




    DiaPie = new DiameterPieChart();
 //   ui->label_Tip->setText(QString::fromStdString("发送\r\n丝径小于档次1 返回E1, 丝径大于档次10 返回E2\r\n接收\r\nD+数字表示直径，例如D233.5\r\nP+数字表示压力，例如P36"));
    LineEdit.push_back(ui->lineEdit_1);
    LineEdit.push_back(ui->lineEdit_2);
    LineEdit.push_back(ui->lineEdit_3);
    LineEdit.push_back(ui->lineEdit_4);
    LineEdit.push_back(ui->lineEdit_5);
    LineEdit.push_back(ui->lineEdit_6);
    LineEdit.push_back(ui->lineEdit_7);
    LineEdit.push_back(ui->lineEdit_8);
    LineEdit.push_back(ui->lineEdit_9);
    LineEdit.push_back(ui->lineEdit_10);

    Labels.push_back(ui->label_11);
    Labels.push_back(ui->label_12);
    Labels.push_back(ui->label_13);
    Labels.push_back(ui->label_14);
    Labels.push_back(ui->label_15);
    Labels.push_back(ui->label_16);
    Labels.push_back(ui->label_17);
    Labels.push_back(ui->label_18);
    Labels.push_back(ui->label_19);
    Labels.push_back(ui->label_20);

      //分类数
    ui->lineEdit_Divides->setText(QString::number(USER_MAX_SIZE_OF_ID));
    //
    connect(ui->pushButton_Divides,&QPushButton::clicked,[=](){RefreshDiv();});


    (ui->lineEdit_1)->setText(QString::number(SIZEPARA[0]));
    (ui->lineEdit_2)->setText(QString::number(SIZEPARA[1]));
    (ui->lineEdit_3)->setText(QString::number(SIZEPARA[2]));
    (ui->lineEdit_4)->setText(QString::number(SIZEPARA[3]));
    (ui->lineEdit_5)->setText(QString::number(SIZEPARA[4]));
    (ui->lineEdit_6)->setText(QString::number(SIZEPARA[5]));
    (ui->lineEdit_7)->setText(QString::number(SIZEPARA[6]));
    (ui->lineEdit_8)->setText(QString::number(SIZEPARA[7]));
    (ui->lineEdit_9)->setText(QString::number(SIZEPARA[8]));
    (ui->lineEdit_10)->setText(QString::number(SIZEPARA[9]));



    connect(ui->lineEdit_1,&QLineEdit::textChanged,[=](){
        SIZEPARA[0] = ui->lineEdit_1->text().toDouble();
        if(SIZEPARA[0]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });
    connect(ui->lineEdit_2,&QLineEdit::textChanged,[=](){
        SIZEPARA[1] = ui->lineEdit_2->text().toDouble();
        if(SIZEPARA[1]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });
    connect(ui->lineEdit_3,&QLineEdit::textChanged,[=](){
        SIZEPARA[2] = ui->lineEdit_3->text().toDouble();
        if(SIZEPARA[2]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });
    connect(ui->lineEdit_4,&QLineEdit::textChanged,[=](){
        SIZEPARA[3] = ui->lineEdit_4->text().toDouble();
        if(SIZEPARA[3]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });
    connect(ui->lineEdit_5,&QLineEdit::textChanged,[=](){
        SIZEPARA[4] = ui->lineEdit_5->text().toDouble();
        if(SIZEPARA[4]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });
    connect(ui->lineEdit_6,&QLineEdit::textChanged,[=](){
        SIZEPARA[5] = ui->lineEdit_6->text().toDouble();
        if(SIZEPARA[5]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });
    connect(ui->lineEdit_7,&QLineEdit::textChanged,[=](){
        SIZEPARA[6] = ui->lineEdit_7->text().toDouble();
        if(SIZEPARA[6]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });
    connect(ui->lineEdit_8,&QLineEdit::textChanged,[=](){
        SIZEPARA[7] = ui->lineEdit_8->text().toDouble();
        if(SIZEPARA[7]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });
    connect(ui->lineEdit_9,&QLineEdit::textChanged,[=](){
        SIZEPARA[8] = ui->lineEdit_9->text().toDouble();
        if(SIZEPARA[8]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });
    connect(ui->lineEdit_10,&QLineEdit::textChanged,[=](){
        SIZEPARA[9] = ui->lineEdit_10->text().toDouble();
        if(SIZEPARA[9]>0){
        UpdateData();
        SAVEPRJPARA;
        }
    });


    DiaPie->refreshItem(ValueOfDi);
    setWindowTitle(Convert("智能设备"));
    showFullScreen();
    QGridLayout *Layout = new QGridLayout(ui->widget);
    Layout->addWidget(DiaPie->GetQChartView());



    //数据显示

            ui->tableWidget->setColumnCount(4);
            ui->tableWidget->setRowCount(10);
            /* 设置 tableWidget */
            ui->tableWidget->setHorizontalHeaderLabels(QStringList() <<Convert("规格") << Convert("数量") << Convert("占比") << Convert("备注"));
            auto Vh = ui->tableWidget->verticalHeader();
            ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems);   // 单个选中
            ui->tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);  // 可以选中多个
            RefreshTableData(ValueOfDi,-1);


    //串口
    QStringList List;
    QList<QSerialPortInfo> Infos = QSerialPortInfo::availablePorts();
    QString SelPORT;
    bool isIn = false;
    for(auto PortInfo : Infos)
    {
        List << PortInfo.portName();

        if(STR_COM==PortInfo.portName()){
            isIn = true;
        }
        if(SelPORT.length() < 2)
        {
            SelPORT = PortInfo.portName();
        }
    }
    if(!isIn && SelPORT.length()>1)
    {
        STR_COM = SelPORT;
    }

    ui->comboBox_COM->addItems(List);
    List.clear();

    List << Baund1200 << Baund2400 << Baund4800 <<Baund9600  << Baund19200 << Baund38400  << Baund57600  << Baund115200 ;
    ui->comboBox_BAUND->addItems(List);
    QComboBox *pCombox = ui->comboBox_BAUND;
    for(int i = 0;i < pCombox->count();i++)
    {
        if(pCombox->itemText(i) == STR_BAUND){
            pCombox->setCurrentIndex(i);
            break;
        }
    }

    List.clear();
    List <<DATA7 << DATA8;
    ui->comboBox_DATA->addItems(List);
    pCombox = ui->comboBox_DATA;
    for(int i = 0;i < pCombox->count();i++)
    {
        if(pCombox->itemText(i) == STR_DATA){
            pCombox->setCurrentIndex(i);
            break;
        }
    }

    List.clear();
    List <<PARNONE <<PARODD <<PAREVEN;
    ui->comboBox_PARITY->addItems(List);
    pCombox = ui->comboBox_PARITY;
    for(int i = 0;i < pCombox->count();i++)
    {
        if(pCombox->itemText(i) == STR_PARITY){
            pCombox->setCurrentIndex(i);
            break;
        }
    }

    List.clear();
    List <<STOP1  << STOP1D5  <<STOP2;
    ui->comboBox_STOP->addItems(List);
    pCombox = ui->comboBox_STOP;
    for(int i = 0;i < pCombox->count();i++)
    {
        if(pCombox->itemText(i) == STR_STOP){
            pCombox->setCurrentIndex(i);
            break;
        }
    }


    connect(ui->comboBox_COM,&QComboBox::currentTextChanged,[=](QString Str){
        std::cout << Str.toLocal8Bit().data()<<std::endl;
        STR_COM = Str;
    });
    connect(ui->comboBox_BAUND,&QComboBox::currentTextChanged,[=](QString Str){
        std::cout << Str.toLocal8Bit().data()<<std::endl;
        STR_BAUND = Str;
    });
    connect(ui->comboBox_DATA,&QComboBox::currentTextChanged,[=](QString Str){
        std::cout << Str.toLocal8Bit().data()<<std::endl;
        STR_DATA = Str;
    });
    connect(ui->comboBox_PARITY,&QComboBox::currentTextChanged,[=](QString Str){
        std::cout << Str.toLocal8Bit().data()<<std::endl;
        STR_PARITY = Str;
    });
    connect(ui->comboBox_STOP,&QComboBox::currentTextChanged,[=](QString Str){
        std::cout << Str.toLocal8Bit().data()<<std::endl;
        STR_STOP = Str;
    });

    if(Mediator::GetIns()->openPort(STR_COM,STR_BAUND,STR_PARITY,STR_DATA,STR_STOP))
    {
        Preference::GetIns()->prj->WriteSettings(-1);
        ui->label_isOpen->setText(Convert("已打开"));
        ui->pushButton_StartSerials->setText(Convert("关闭串口"));
    }
    else
    {
        ui->label_isOpen->setText(Convert("未打开"));
        ui->pushButton_StartSerials->setText(Convert("打开串口"));
    }

//    connect(ui->pushButton_StartSerials,&QPushButton::clicked,[=](){

   // });

    UpdateData();



}

MainWindow::~MainWindow()
{
    delete ui;
    delete  DiaPie;
}

void MainWindow::on_pushButton_Quit_clicked()
{
    exit(0);
    for(auto &vd :ValueOfDi){
        vd.second++;
    }
    DiaPie->UpdateSlice(ValueOfDi);
}

void MainWindow::on_pushButton_Clear_clicked()
{
    ui->label_Status->setStyleSheet("font-size:88px;color:rgb(0,255,0)");
    ui->label_Status->setText("正常");
}

void MainWindow::on_pushButton_OpenFile_clicked()
{
    QDesktopServices::openUrl(QUrl("XLS", QUrl::TolerantMode));
}

void MainWindow::on_pushButton_MinWindow_clicked()
{
    this->showMinimized();
}

void MainWindow::on_pushButton_StartSerials_clicked()
{
    if(!Mediator::GetIns()->isOpened())
    {
        if(Mediator::GetIns()->openPort(STR_COM,STR_BAUND,STR_PARITY,STR_DATA,STR_STOP))
        {
            Preference::GetIns()->prj->WriteSettings(-1);
            ui->label_isOpen->setText(Convert("已打开"));
            ui->pushButton_StartSerials->setText(Convert("关闭串口"));
        }
        else
        {
            ui->label_isOpen->setText(Convert("未打开"));
            ui->pushButton_StartSerials->setText(Convert("打开串口"));
        }
    }
    else
    {
        Mediator::GetIns()->closePort();
        ui->label_isOpen->setText(Convert("未打开"));
        ui->pushButton_StartSerials->setText(Convert("打开串口"));
    }
}
